package com.zs.admin.service.wisdbook.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zs.admin.service.wisdbook.IWisdbookAsyncService;
import com.zs.common.entity.wisdbook.Wisdbook;
import com.zs.common.entity.wisdbook.WisdbookPage;
import com.zs.common.mapper.WisdbookMapper;
import com.zs.common.mapper.WisdbookPageMapper;
import com.zs.common.plugin.storage.StorageDriver;
import com.zs.common.util.YmlUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @title: WisdbookAsyncServiceImpl
 * @Author wkm
 * @Date: 2023/5/26 17:25
 * @Note 注释：
 */
@Service
public class WisdbookAsyncServiceImpl implements IWisdbookAsyncService {

    private static final Logger log = LoggerFactory.getLogger(WisdbookAsyncServiceImpl.class);
    public static final float DEFAULT_DPI = 200;
    public static final String DEFAULT_FORMAT = "jpg";

    @Resource
    WisdbookMapper wisdbookMapper;
    @Resource
    WisdbookPageMapper wisdbookPageMapper;

    @Override
    public void executePdfToPageImg() {
        List<Wisdbook> list = pdflist();
        for (int i = 0; i < list.size(); i++) {
            Wisdbook wisdbook = list.get(i);
            int n = pdfToPages(wisdbook);
        }
    }

    @Override
    public List<Wisdbook> pdflist() {
        QueryWrapper<Wisdbook> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        queryWrapper.isNotNull("pdf_url");
        queryWrapper.ne("pdf_url", "");
        queryWrapper.eq("create_page", 0);
        queryWrapper.orderByAsc("id");
        List<Wisdbook> list = wisdbookMapper.selectList(queryWrapper);
        return list;
    }

    @Override
    public int pdfToPages(Wisdbook wisdbook) {
        log.info("书籍id={}，pdf={}，pdf转pageImg开始：", wisdbook.getId(), wisdbook.getPdfUrl());
        Wisdbook model = new Wisdbook();
        model.setId(wisdbook.getId());
        model.setCreatePage(1);
        wisdbookMapper.updateById(model);
        String https = YmlUtils.get("ossResource.https");
        List<String> list = pdfToImgList(https + wisdbook.getPdfUrl(), wisdbook.getId());
        for (int i = 0; i < list.size(); i++) {
            log.info("书籍id={}，生成页图={}",wisdbook.getId(),list.get(i));
            WisdbookPage page = new WisdbookPage();
            page.setBookId(wisdbook.getId());
            page.setPageImg(list.get(i));
            page.setPageName(String.valueOf(i+1));
            page.setPageNum(i+1);
            page.setCreateTime(System.currentTimeMillis() / 1000);
            wisdbookPageMapper.insert(page);
        }
        model.setCreatePage(2);
        model.setMarkStatus(1);
        wisdbookMapper.updateById(model);
        return list.size();
    }


    /**
     * @param pdfUrl pdf文件的url地址
     * @return List 图片oss地址
     */
    public List<String> pdfToImgList(String pdfUrl, Integer bookId) {
        List<String> list = new ArrayList<>();
        PDDocument pdDocument = null;
        try {
            //图像合并使用参数
            // 总宽度
            int width = 0;
            // 保存一张图片中的RGB数据
            int[] singleImgRGB;
            int shiftHeight = 0;
            //保存每张图片的像素值
            BufferedImage imageResult = null;
            pdDocument = PDDocument.load(url2InputStream(pdfUrl));
            PDFRenderer renderer = new PDFRenderer(pdDocument);
            //循环每个页码
            for (int i = 0, len = pdDocument.getNumberOfPages(); i < len; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, DEFAULT_DPI, ImageType.RGB);
                int imageHeight = image.getHeight();
                int imageWidth = image.getWidth();
                //计算高度和偏移量
                //使用第一张图片宽度;
                width = imageWidth;
                //保存每页图片的像素值
                imageResult = new BufferedImage(width, imageHeight, BufferedImage.TYPE_INT_RGB);
                //这里有高度，可以将imageHeight*len，我这里值提取一页所以不需要
                singleImgRGB = image.getRGB(0, 0, width, imageHeight, null, 0, width);
                // 写入流中
                imageResult.setRGB(0, shiftHeight, width, imageHeight, singleImgRGB, 0, width);
                // 写图片
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write(imageResult, DEFAULT_FORMAT, os);
                StorageDriver storageDriver = new StorageDriver(YmlUtils.get("spring.profiles.active"));
                String key = "bookpage/" + bookId + "/" + UUID.randomUUID() + "." + DEFAULT_FORMAT;
                storageDriver.uploadImgByte(os.toByteArray(), key);
                list.add(key);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (pdDocument != null) {
                try {
                    pdDocument.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }


    /**
     * url 转 InputStream
     *
     * @param fileUrl
     * @return
     * @throws IOException
     */
    public static InputStream url2InputStream(String fileUrl) {
        InputStream in = null;
        try {
            URL url = new URL(fileUrl);
            URLConnection conn = url.openConnection();
            conn.setConnectTimeout(30 * 1000);  // 连接超时:30s
            conn.setReadTimeout(1 * 1000 * 1000); // IO超时:1min
            conn.connect();
            // 创建输入流读取文件
            in = conn.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return in;
    }

}

